package biz

import (
	"New-lesson-part2/custom_error"
	"New-lesson-part2/internal"
	"New-lesson-part2/model"
	"New-lesson-part2/proto/pb"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/golang/protobuf/ptypes/empty"
)

//Category 分类相关操作

func (p ProductServer) CreateCategory(ctx context.Context, req *pb.CategoryItemReq) (*pb.CategoryItemRes, error) {
	var res *pb.CategoryItemRes
	var categoryReq model.CateGory
	r := internal.DB.First(&categoryReq, req.Id)
	//if r.Error != nil {
	//	fmt.Println(r.Error)
	//	return nil, errors.New(custom_error.CategorySystemError)
	//}
	if r.RowsAffected != 0 {
		return nil, errors.New(custom_error.CategoryDataIsExists)
	}
	categoryReq.ParentCategoryID = 1
	if req.Level > 1 {
		res.ParentCategoryId = req.ParentCategoryId
	}
	categoryReq.ID = req.Id
	categoryReq.Name = req.Name
	categoryReq.Level = req.Level

	save := internal.DB.Save(&categoryReq)
	if save.Error != nil {
		return nil, errors.New(custom_error.CategorySystemError)
	}
	if save.RowsAffected < 1 {
		return nil, errors.New(custom_error.CategoryDataCreationFailed)
	}
	res = ConvertCategoryModel2pb(categoryReq)
	return res, nil
}

func (p ProductServer) GetAllCategoryList(ctx context.Context, empty *empty.Empty) (*pb.CategoriesRes, error) {
	var cateAll pb.CategoriesRes      //最终返回的数据类型
	var categoryList []model.CateGory //数据库查询出来的数据存放位置
	var count int64

	var infoResList []*pb.CategoryItemRes //返回的总行数
	//r := internal.DB.Where(&model.CateGory{Level: 1}).Count(&count).Preload("CateGory").Find(&categoryList)
	r := internal.DB.Where("Level >=?", 1).Find(&categoryList)
	//这里使用的是同一张表中的不同字段进行预加载.其中SubCategory.SubCategory是这张表中的SubCategory这个字段.
	//意思是将这张表中隶属于Level:1级别的所有关联字段都查询出来.并写到categoryList中
	//if r.Error != nil {
	//	return nil, errors.New(custom_error.CategorySystemError)
	//}
	if r.RowsAffected < 1 {
		return nil, errors.New(custom_error.CategoryDoesNotExist)
	}

	for _, i := range categoryList {
		infoResList = append(infoResList, ConvertCategoryModel2pb(i))
		fmt.Println(i.Name, i.ID, i.ParentCategoryID, i.Level)
	}
	cateAll.InfoResList = infoResList
	cateAll.Total = int32(count)
	b, err := json.Marshal(cateAll.InfoResList)
	if err != nil {
		fmt.Println(err)
	}
	cateAll.CategoryJsonFormat = string(b)

	return &cateAll, nil
}

func (p ProductServer) GetSubCategory(ctx context.Context, req *pb.CategoriesReq) (*pb.SubCategoriesRes, error) {
	var cateRes pb.SubCategoriesRes
	var cateModel model.CateGory
	var cateSubList []model.CateGory

	r := internal.DB.First(&cateModel, req.Id)
	if r.Error != nil {
		return nil, errors.New(custom_error.CategorySystemError)
	}
	find := internal.DB.Where(&model.CateGory{ParentCategoryID: cateModel.ID}).Where("id !=?", req.Id).Find(&cateSubList)
	for _, i := range cateSubList {
		cateRes.SubCategoryList = append(cateRes.SubCategoryList, ConvertCategoryModel2pb(i))
	}
	if find.Error != nil {
		return nil, errors.New(custom_error.CategorySystemError)
	}
	b, err := json.Marshal(cateRes.SubCategoryList)
	if err != nil {
		fmt.Println(err)
	}
	cateRes.CategoryJsonFormat = string(b)
	return &cateRes, nil
}

func (p ProductServer) DeleteCategory(ctx context.Context, req *pb.CategoryDelReq) (*empty.Empty, error) {
	var cate model.CateGory
	var subItm []int
	r := internal.DB.First(&cate, req.Id) //可以得到当前分类的id 以及当前分类所属的父分类id
	if r.Error != nil {
		return nil, errors.New(custom_error.CategorySystemError)
	}
	if r.RowsAffected < 1 {
		return nil, errors.New(custom_error.CategoryDoesNotExist)
	}
	find := internal.DB.Model(&model.CateGory{}).Select("id").Where("ParentCategoryID = ?", req.Id).Find(&subItm)
	if find.Error != nil {
		return nil, errors.New(custom_error.CategorySystemError)
	}
	tx := internal.DB.Delete(&cate, req.Id, subItm)
	if tx.Error != nil {
		return nil, errors.New(custom_error.CategorySystemError)
	}
	if tx.RowsAffected < 1 {
		return nil, errors.New(custom_error.CategoryDoesNotExist)
	}
	return &empty.Empty{}, nil
}

func (p ProductServer) UpdateCategory(ctx context.Context, req *pb.CategoryItemReq) (*empty.Empty, error) {
	//TODO implement me
	panic("implement me")
}

func ConvertCategoryModel2pb(gory model.CateGory) *pb.CategoryItemRes {
	return &pb.CategoryItemRes{
		Id:               gory.ID,
		Name:             gory.Name,
		ParentCategoryId: gory.ParentCategoryID,
		Level:            gory.Level,
	}
}
